<?php

namespace App\Http\Middlewares;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Route;

class CheckWechatBrowser
{
    /**
     * 处理传入的请求
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        // 检查是否在微信浏览器中
        if ($this->isWechatBrowser($request) && !Auth::check()) {
            // 保存当前URL以便登录后重定向回来
            session(['login_redirect' => $request->fullUrl()]);

            // 重定向到微信登录
            return redirect()->route('wechat.login');
        }

        return $next($request);
    }

    /**
     * 判断是否是微信浏览器
     *
     * @param  \Illuminate\Http\Request  $request
     * @return bool
     */
    protected function isWechatBrowser(Request $request)
    {
        $userAgent = $request->header('User-Agent');
        return strpos($userAgent, 'MicroMessenger') !== false;
    }
}
